import React from 'react';
import { Text, View, StyleSheet, Image, TextInput, ImageBackground, ToastAndroid } from 'react-native';
import CheckBox from 'react-native-check-box';
import PropTypes from 'prop-types';
import { observer, inject } from 'mobx-react';
import { LoginApi } from '../api';
import Button from '../components/base/Button';
import BackPressComponent from '../components/base/BackPress';
import LoginModal from '../components/LoginModal';
import LoginStoreObj from '../store/LoginStore';
import SafeAreaViewPlus from '../components/base/SafeAreaViewPlus';
import GlobalStyles from '../style/GlobalStyles';
import px from '../utils/px';
import NavigationUtil from '../navigation/NavigationUtil';

@inject(['LoginStore'])
@observer
export default class LoginScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            code: '',
            codeText: '获取验证码',
            codeTextStyle: { color: 'rgb(51,51,51)' },
            modalTitle: '验证码输入错误',
            isChecked: false
        };
        NavigationUtil.navigation = this.props.navigation;
        this.backPress = new BackPressComponent({ backPress: () => this.onBackPress() });
    }
    // 设置状态属性
    static propTypes = {
        LoginStore: PropTypes.objectOf(LoginStoreObj).isRequired
    };
    // 配置 Navigation 设置
    static navigationOptions = {
        title: '登录页',
        header: null
    };

    componentDidMount() {
        NavigationUtil.willFocus(() => {
            this.backPress.componentDidMount();
        });
        NavigationUtil.willBlur(() => {
            this.backPress.componentWillUnmount();
        });
    }

    componentWillUnmount() {
        // 清空定时器
        this.timer && clearTimeout(this.timer);
    }

    // 监听安卓返回键
    onBackPress = () => {
        // 最近2秒内按过back键，可以退出应用。
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) return false;
        this.lastBackPressed = Date.now();
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
        return true;
    };

    /**
     * 输入手机号
     * @param {string} phone - 用户手机号
     */
    handlePhoneChange(phone) {
        this.setState({ phone: phone });
    }

    /**
     * 输入验证码
     * @param {string} code - 验证码
     */
    handleCodeChange(code) {
        this.setState({ code: code });
    }

    // 获取验证码
    getCode() {
        const { LoginStore } = this.props;
        const { phone } = this.state;
        if (phone.length < 11 || !(/^1\d{10}$/.test(phone))) {
            this.setState({ modalTitle: '请输入正确的手机号' });
            this.loginModal.show();
            return;
        }
        if (!LoginStore.time) {
            LoginApi.getCode({ username: phone }).then(ret => {
                const { code } = ret;
                if (code && code.code === 2000) {
                    LoginStore.resetTime();
                    this.setState({
                        codeText: `${LoginStore.time}s后重试`,
                        codeTextStyle: { color: 'rgb(51,51,51)' }
                    });
                    this.timer = setInterval(() => {
                        if (LoginStore.time) {
                            LoginStore.decreaseTime();
                            this.setState({ codeText: `${LoginStore.time}s后重试` });
                        } else {
                            clearInterval(this.timer);
                            this.setState({
                                codeText: '再次获取',
                                codeTextStyle: { color: GlobalStyles.MAIN_COLOR }
                            });
                        }
                    }, 1000);
                } else {
                    this.setState({ modalTitle: code.message }, () => {
                        this.loginModal.show();
                    });
                }
            });
        }
    }

    allowLogin() {
        const { phone, code, isChecked } = this.state;
        return (phone.length >= 11 && code.length >= 4 && isChecked);
    }

    // 用户登录
    userLogin() {
        const { phone, code } = this.state;
        if (!this.allowLogin()) return;
        LoginApi.userLogin({ username: phone, code }).then(ret => {
            const { code, data } = ret;
            if (code.code === 2000) {
                global.storage.save({
                    key: 'userInfo',
                    data: {
                        accountId: data.accountId,
                        token: data.token
                    }
                });
                NavigationUtil.goPage('App');
            } else {
                this.setState({ modalTitle: '验证码输入错误' }, () => {
                    this.loginModal.show();
                });
            }
        });
    }

    // 勾选用户协议
    handleCheckBoxChange() {
        this.setState(state => ({ isChecked: !state.isChecked }));
    }

    // 查看比价协议
    goAgreementPage() {
        NavigationUtil.goPage('Agreement');
    }

    render() {
        const { isChecked, phone, code, codeTextStyle, codeText, modalTitle } = this.state;
        let BtnColor = this.allowLogin() ? GlobalStyles.MAIN_COLOR : GlobalStyles.CANCEL_COLOR;
        return (
            <SafeAreaViewPlus>
                <View style={styles.container}>
                    <Image
                        style={styles.logo}
                        source={require('../assets/images/logo.png')}/>
                    <View style={styles.login}>
                        <ImageBackground
                            resizeMode="center"
                            source={require('../assets/images/rectangle.png')}
                            style={styles.loginBg}>
                            <View style={styles.phone}>
                                <Text style={styles.text}>手机号</Text>
                                <TextInput
                                    value={phone}
                                    style={styles.iptPhone}
                                    maxLength={11}
                                    keyboardType={'numeric'}
                                    placeholder={'请输入手机号'}
                                    onChangeText={phone => this.handlePhoneChange(phone)}/>
                            </View>
                        </ImageBackground>
                        <ImageBackground
                            resizeMode="center"
                            source={require('../assets/images/rectangle.png')}
                            style={[styles.loginBg, { marginTop: px(30) }]}>
                            <View style={styles.phone}>
                                <Text style={styles.text}>验证码</Text>
                                <TextInput
                                    value={code}
                                    style={styles.iptCode}
                                    maxLength={4}
                                    placeholder={'请输入验证码'}
                                    onChangeText={code => this.handleCodeChange(code)}/>
                                <Text
                                    onPress={() => this.getCode()}
                                    style={[styles.getCode, codeTextStyle]}>{codeText}</Text>
                            </View>
                        </ImageBackground>
                    </View>
                    <Button.HeightLight
                        onPress={() => this.userLogin()}
                        btnStyle={[styles.btn, { backgroundColor: BtnColor }]}
                        btnText={[styles.btnText]}
                        title="登录/注册"/>
                    <View style={styles.agreement}>
                        <CheckBox
                            onClick={() => this.handleCheckBoxChange()}
                            checkedImage={<Image style={{ width: px(32), height: px(32) }}
                                                 source={require('../assets/icon/checkbox_checked.png')}/>}
                            unCheckedImage={<Image style={{ width: px(32), height: px(32) }}
                                                   source={require('../assets/icon/checkbox_unchecked.png')}/>}
                            isChecked={isChecked}/>
                        <Text style={styles.agreementText}>
                            &nbsp;&nbsp;已阅读并同意《
                            <Text
                                style={styles.agreementPage}
                                onPress={() => this.goAgreementPage()}>货比三价使用协议&隐私政策</Text>
                            》
                        </Text>
                    </View>
                </View>
                <LoginModal title={modalTitle} ref={c => (this.loginModal = c)}/>
            </SafeAreaViewPlus>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        display: 'flex',
        alignItems: 'center',
        width: GlobalStyles.DEVICE_WIDTH,
        height: GlobalStyles.DEVICE_HEIGHT
    },
    logo: {
        marginTop: px(232),
        height: px(160),
        width: px(160)
    },
    login: {
        display: 'flex',
        alignItems: 'center',
        marginTop: px(99),
        marginBottom: px(60),
        width: '100%',
        paddingLeft: px(45),
        paddingRight: px(45)
    },
    loginBg: {
        width: '100%',
        height: px(100)
    },
    phone: {
        position: 'relative',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        width: '100%',
        height: '100%'
    },
    text: {
        fontSize: GlobalStyles.FONT_SIZE,
        color: 'rgb(51,51,51)',
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL,
        paddingLeft: px(30)
    },
    iptPhone: {
        paddingLeft: px(30),
        width: '100%',
        fontSize: GlobalStyles.FONT_SIZE,
        color: 'rgb(51,51,51)',
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL
    },
    iptCode: {
        paddingLeft: px(30),
        flex: 1,
        fontSize: GlobalStyles.FONT_SIZE,
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL
    },
    getCode: {
        marginRight: px(30),
        fontSize: GlobalStyles.FONT_SIZE,
        color: GlobalStyles.CANCEL_COLOR
    },
    btn: {
        width: GlobalStyles.DEVICE_WIDTH - px(90),
        borderRadius: px(8),
        height: px(90)
    },
    btnText: {
        fontSize: GlobalStyles.FONT_SIZE
    },
    agreement: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: px(38)
    },
    agreementText: {
        fontSize: px(28),
        fontFamily: GlobalStyles.FONT_FAMILY_NORMAL,
        color: GlobalStyles.CANCEL_COLOR
    },
    agreementPage: {
        color: '#E83922'
    }
});
